package downloader

import (
	"errors"
	"io/ioutil"
	"net/http"
	"regexp"
)

//Downloads the specified URL and returns it as a byte slice
func getPage(url string) (result []byte, err error) {
	resp, err := http.Get(url)
	if err != nil {
		return
	}

	result, err = ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	return
}

//Returns first submatch of regex inside the byte slice.
func findLink(regex string, page []byte) (url string, err error) {
	r, err := regexp.Compile(regex)
	if err != nil {
		return
	}
	match := r.FindSubmatch(page)
	if match == nil {
		url = ""
		err = errors.New("findLink: Couldn't find link on page.")
		return
	}
	if len(match) < 2 {
		url = ""
		err = errors.New("findLink: No submatch.")
		return
	}
	url = string(match[1])
	return
}

func DownloadComic(regex string, url string, prependURL string) (img []byte, err error) {
	page, err := getPage(url)
	if err != nil {
		return
	}

	link, err := findLink(regex, page)
	if err != nil {
		return
	}
	img, err = getPage(prependURL + link)
	return
}
